import {useRouter} from "vue-router";
import {onMounted, reactive, ref} from "vue";
import user from "../../service/service";
import {ElMessage} from 'element-plus'
import "element-plus/theme-chalk/el-message.css"
import admin_service from "../../service/admin_service";

export default function Login() {
    // 初始化事件
    onMounted(()=>{
        let token = localStorage.getItem('token')
        if (token){
            admin_service.auth().then(r =>{
                if (r.data.code === 200){
                    router.push('/admin')
                }
            })
        }
    })
    const router = useRouter()
    let username = ref('')
    let password = ref('')
    const loginBtn = () => {
        user.login({username: username.value, password: password.value}).then(res => {
            let data = res.data
            if (data.code === 200) {
                localStorage.setItem("token", data.token)
                localStorage.setItem("username", username.value)
                ElMessage.success("登录成功")
                router.push('/admin')
            } else {
                ElMessage.error("登录失败")
            }
        })
        // router.push('/admin')
    }
    return {
        loginBtn,
        username,
        password,
    }
}